<?php
class YYK{
	/*核心框架存放路径*/
	private static $YYK_path="";

	/*当前应用存放路径*/
	public static $APP_path="";

	/*当前应用入口URL*/
	public static $APP_url="";

	/*配置信息*/
	public static $config;

	/*当前访问的rest资源名*/
	public static $resourceName;
	private static $resourceClass;
	public static $httpMethod;

	public static $debug;
	public static $defaultLang="";

	/**
	* 系统入口
	* 并且支持配置自动加载路径
	* @return void
	*/
	public static function start($appDirectory,$conf='config.php', $debug=false){
		//var_dump( $_SERVER);
		// 设定错误和异常处理
		//register_shutdown_function(array('YYK','fatalError'));
		self::$debug = $debug;
		set_error_handler(array('YYK','appError'), E_ALL);
		set_exception_handler(array('YYK','appException'));
		//取当前框架路径
		self::$YYK_path = pathinfo(__FILE__, PATHINFO_DIRNAME);
		//取当前项目路径
		self::$APP_path = realpath( $appDirectory );
		//self::$APP_path = pathinfo(realpath( $appDirectory), PATHINFO_DIRNAME);//pathinfo($_SERVER["SCRIPT_FILENAME"], PATHINFO_DIRNAME);

		//加载常用方法
		include self::$YYK_path. DIRECTORY_SEPARATOR . 'common.php';

		if (file_exists(self::$APP_path. DIRECTORY_SEPARATOR . 'common.php')) {
			//加载项目自定义方法
			include self::$APP_path. DIRECTORY_SEPARATOR . 'common.php';
		}
		//加载默认配置
		/*
		$tmp = array();
		if (file_exists(self::$YYK_path. DIRECTORY_SEPARATOR . 'config.php')) {
		$tmp = include self::$YYK_path. DIRECTORY_SEPARATOR . 'config.php';
		}
		*/

		//加载用户配置
		$conf = empty($conf) ? "config.php" : $conf;
		if (file_exists(self::$APP_path. DIRECTORY_SEPARATOR . $conf)){
			self::$config = include self::$APP_path. DIRECTORY_SEPARATOR . $conf;
		}

		//合并配置
		/*
		self::$config = array_merge($tmp, self::$config);
		unset($tmp);
		*/

		// 注册AUTOLOAD方法
		//加载用户控制器类
		spl_autoload_register(array('YYK', 'appCtrl'));

		//加载用户模型类
		spl_autoload_register(array('YYK', 'appModel'));

		//加载YYK核心类
		spl_autoload_register(array('YYK', 'YYKClass'));

		//加载框架扩展类

		//加载第三方类
		spl_autoload_register(array('YYK', 'otherClass'));

		//启动session
		session_start();

		//设置时区
		date_default_timezone_set(self::$config['timeZone']);

		//启用语言包
		if (isset(self::$config['useMultiLang']) && self::$config['useMultiLang']==true ) {
			$lang = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
			self::$defaultLang = $lang[0];
		}

		//路由分析
		self::$resourceName = self::parseRoute();

		if (self::$resourceName){
			self::$httpMethod = ucfirst(strtolower( $_SERVER['REQUEST_METHOD'] ));
			// echo self::$httpMethod;
			header('access-control-allow-credentials:true');
			header('access-control-allow-methods:GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS');
			header('access-control-allow-origin:*');
			header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Auth-Token");
			header('access-control-allow-Authorization:*');
			if (strtoupper(self::$httpMethod) == 'OPTIONS') {
				// header('HTTP 200 OK');
				exit();
			}
			self::$resourceClass = self::$resourceName . self::$httpMethod;

			if (file_exists(self::$APP_path . DIRECTORY_SEPARATOR . 'Rest' . DIRECTORY_SEPARATOR .self::$resourceName.DIRECTORY_SEPARATOR.self::$resourceClass.'.class.php')){
				unset($_REQUEST);
				$_REQUEST['GET'] = $_GET;
				if (self::$httpMethod != 'Get') {
					$reqMethod = '_' . strtoupper(self::$httpMethod);
					$tmp = file_get_contents('php://input');
					if ($array = json_decode($tmp, true)) {
						$reqData = array();
						foreach ($array as $key => $value) {
							$reqData[$key] = $value;
						}
						$$reqMethod = $reqData;
					}
					else{
						parse_str($tmp, $$reqMethod);
					}
					$_REQUEST[substr($reqMethod,1)] = $$reqMethod;
				}
				else{
					$reqMethod = '_GET';
					$$reqMethod = $_GET;
				}
				$instance = new self::$resourceClass();
				$instance->exec($$reqMethod, $_GET);
				// self::export($data);
			}
			else{
				// 没找到对应类, 返回 404
				header($_SERVER['SERVER_PROTOCOL'] . ' 404 NOT FOUND');
				exit(0);
				// self::export(['httpStatus' => 404]);
			}
		}
		else{
			//没有解析到资源地址
			// self::export(['httpStatus' => 404]);
			header($_SERVER['SERVER_PROTOCOL'] . ' 404 NOT FOUND');
			exit(0);
		}
	}


	/**
	* 自动加载用户控制器类库
	* 并且支持配置自动加载路径
	* @param string $class 对象类名
	* @return void
	*/
	public static function appCtrl($class){
		$path = self::$APP_path . DIRECTORY_SEPARATOR . 'Rest' . DIRECTORY_SEPARATOR . $class . '.class.php';

		if (file_exists($path)) {
			include_once($path);
			return false;
		}

		$path = self::$APP_path . DIRECTORY_SEPARATOR . 'Rest' . DIRECTORY_SEPARATOR .substr($class, 0, strripos($class, self::$httpMethod)).DIRECTORY_SEPARATOR.$class.'.class.php';
		if (file_exists($path)) {
			include_once($path);
		}
	}

	/**
	* 自动加载用户模型类库
	* 并且支持配置自动加载路径
	* @param string $class 对象类名
	* @return void
	*/
	public static function appModel($class){
		if (file_exists(self::$APP_path . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR . $class . '.class.php')) {
			include_once(self::$APP_path . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR  . $class . '.class.php');
		}
	}

	public static function YYKClass($class){
		$class = strtolower($class);
		if (file_exists(self::$YYK_path . DIRECTORY_SEPARATOR . $class . '.class.php')) {
			include_once(self::$YYK_path . DIRECTORY_SEPARATOR . $class . '.class.php');
		}
	}

	public static function otherClass($class){
		if (file_exists(self::$YYK_path . DIRECTORY_SEPARATOR . 'lib'. DIRECTORY_SEPARATOR . $class . DIRECTORY_SEPARATOR . $class . '.class.php')) {
			include_once(self::$YYK_path . DIRECTORY_SEPARATOR . 'lib'. DIRECTORY_SEPARATOR . $class . DIRECTORY_SEPARATOR . $class . '.class.php');
		}
		else{
			if (substr($class, -4) == 'Ctrl') {
				//_404();
			}
			else{
				E('Not Found Class: '.$class);
			}
		}
	}

	//路由分析
	public static function parseRoute(){
		if (isset($_GET['s']) && strlen($_GET['s'])>0){
			$_SERVER['PATH_INFO'] = $_GET['s'];
			// $_GET = [];
			unset($_GET['s']);
		}

		// echo $_SERVER['PATH_INFO'];exit;
		if (isset($_SERVER['PATH_INFO']) && strlen($_SERVER['PATH_INFO'])>1){
			$pathInfo = $_SERVER['PATH_INFO'];
			$pathInfo = trim($pathInfo, '/');
			$arr = explode(self::$config['pathinfoSeparator'], trim($pathInfo, '/'));

			//pathinfo非路由
			if ((!isset($arr[0])) || strlen($arr[0])==0) {
				return false;
			}

			for ($i=1; ; $i+=2) {
				if(!isset($arr[$i+1])) break;
				$_GET[$arr[$i]] = $arr[$i+1];
			}
			return $arr[0];
		}
		else{
			// 输出错误提示或帮助信息
			return false;
		}
	}

	public static function appError($fehlercode, $fehlertext, $fehlerdatei, $fehlerzeile){
		if (self::$debug) {
			echo "<b>Custom error:</b> [$fehlercode] $fehlertext";
			echo " Error on line $fehlerzeile in $fehlerdatei<br />";
		}
		return true;
	}

	public static function appException($exception){
		if (self::$debug) {
			echo "Uncaught exception: " , $exception->getMessage(), "<br>";
		}
		return true;
	}

	public static function getYYK_path(){
		return self::$YYK_path;
	}
}
